<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <el-form :inline="true" :model="params.entity"
                 style="padding-bottom: 0px;">
          <el-form-item label="商户来源">
            <el-select v-model="params.entity.shopSource" clearable
                       placeholder="请选择商户来源" style="width:160px">
              <el-option :label="'抖音'" :value=0></el-option>
              <el-option :label="'美团'" :value=1></el-option>
              <el-option :label="'系统自建'" :value=2></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域合伙人">
            <el-input v-model="params.entity.adminName"
                      placeholder="请输入所属区域合伙人"/>

            <!--          <el-form-item label="所属团队长">-->
            <!--            <el-tree-select-->
            <!--                v-model="params.entity.searchAdminIds"-->
            <!--                :data="adminTrees"-->
            <!--                multiple-->
            <!--                :render-after-expand="false"-->
            <!--                show-checkbox-->
            <!--                check-strictly-->
            <!--                check-on-click-node-->
            <!--                style="width: 240px"-->
            <!--            />-->
            <!--          </el-form-item>-->
            <!--          <el-form-item label="门店ID">-->
            <!--            <el-input v-model="params.entity.poiId"-->
            <!--                      placeholder="请输入门店ID"/>-->
          </el-form-item>
          <el-form-item label="门店名称">
            <el-input v-model="params.entity.poiName"
                      placeholder="请输入门店名称"/>
          </el-form-item>
          <!--          <el-form-item label="账户名称">-->
          <!--            <el-input v-model="params.entity.accountName"-->
          <!--                      placeholder="请输入账户名称"/>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="searchData">查询</el-button>
            <el-button type="primary" :icon="Download" @click="searchExportData">导出</el-button>
            <!--            <el-button type="primary" :icon="Plus" v-if="userOperaPermit"-->
            <!--                       @click="addDialog">新增-->
            <!--            </el-button>-->
          </el-form-item>
        </el-form>
      </div>
    </template>

    <el-button type="primary" :icon="EditPen" @click="updateCity">变更城市</el-button>
    <el-table v-loading="loading"
              :data="tableData.list" style="width: 100%" height="500"
              :default-sort="{ prop: 'date', order: 'descending' }"
              @selection-change="handleSelectionChange">
            <el-table-column fixed type="selection" width="55"/>
      <!--      <el-table-column prop="id" label="ID" fixed show-overflow-tooltip/>-->

      <el-table-column prop="poiName" fixed label="门店名称" width="160" show-overflow-tooltip/>
      <el-table-column prop="ownerUserName" fixed label="商户账号"
                       show-overflow-tooltip/>
      <el-table-column prop="adminName" fixed label="所属区域合伙人" width="120"
                       show-overflow-tooltip/>
      <el-table-column prop="city" fixed label="归属城市" width="160" show-overflow-tooltip/>
      <!--      <el-table-column prop="shopSourceName" label="商户来源" show-overflow-tooltip/>-->
      <el-table-column prop="shopSourceName" label="商户来源" width="100"/>
      <el-table-column prop="poiId" label="门店ID" width="200"/>

      <el-table-column prop="address" label="营业执照地址" width="260"
                       show-overflow-tooltip/>
      <el-table-column prop="latitude" label="维度" show-overflow-tooltip/>
      <el-table-column prop="longitude" label="经度" show-overflow-tooltip/>

      <el-table-column prop="corporation" label="法人名称" show-overflow-tooltip/>
      <el-table-column prop="corporationPhone" label="法人手机"
                       show-overflow-tooltip/>
      <el-table-column prop="storePhone" label="门店手机" show-overflow-tooltip/>
      <el-table-column prop="businessLicense" label="营业执照名称"
                       show-overflow-tooltip/>
      <el-table-column prop="sanitaryLicensePhoto" label="营业执照照片">
        <template #default="scope">
          <el-image
              v-if="scope.row.sanitaryLicensePhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.sanitaryLicensePhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.sanitaryLicensePhotos"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="dredgeDouyin" label="之前开通抖音">
        <template #default="scope">
          {{
            scope.row.dredgeDouyin == 0 ? '没有' :
                scope.row.dredgeDouyin == 1 ? '自己上的团购' : scope.row.dredgeDouyin == 2 ? '加盟其他品牌' : ''
          }}
        </template>
      </el-table-column>
      <el-table-column prop="dredgeBuy" label="之前开通团购">
        <template #default="scope">
          {{
            scope.row.dredgeDouyin == 0 ? '未绑定' : scope.row.dredgeDouyin == 1 ? '已绑定' : ''
          }}
        </template>
      </el-table-column>
      <el-table-column prop="businessLicensePhotos" label="营业执照照片">
        <template #default="scope">
          <el-image
              v-if="scope.row.businessLicensePhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.businessLicensePhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.businessLicensePhotos"
              :initial-index="4"
              fit="cover"
          />
        </template>


      </el-table-column>
      <el-table-column prop="corporationPshoto" label="法人照片">
        <template #default="scope">
          <el-image
              v-if="scope.row.corporationPhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.corporationPhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.corporationPhotos"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="corporationCard" label="法人收款账号"
                       show-overflow-tooltip/>
      <el-table-column prop="corporationCardBank" label="法人收款账号开户行"
                       show-overflow-tooltip/>
      <el-table-column prop="doorPhotos" label="门头照">
        <template #default="scope">
          <el-image
              v-if="scope.row.doorPhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.doorPhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.doorPhotos"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="evnPhotos" label="室内环境照">
        <template #default="scope">
          <el-image
              v-if="scope.row.evnPhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.evnPhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.evnPhotos"
              :initial-index="4"
              fit="cover"/>
        </template>
      </el-table-column>
      <el-table-column prop="douyinPhotos" label="抖音截图">
        <template #default="scope">
          <el-image
              v-if="scope.row.douyinPhotos.length> 0"
              style="width: 100px; height: 100px"
              :src="scope.row.douyinPhotos[0]"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.douyinPhotos"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="deliveryAddress" label="收货地址"
                       show-overflow-tooltip/>
      <el-table-column prop="businessHour" label="营业时间" show-overflow-tooltip/>
      <el-table-column prop="examineVerifyName" label="审核状态" width="120"
                       show-overflow-tooltip/>
      <!--      <el-table-column prop="accountId" label="账户信息" show-overflow-tooltip/>-->
      <!--      <el-table-column prop="accountName" label="账户名称"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="latitude" label="维度" show-overflow-tooltip/>-->
      <!--      <el-table-column prop="longitude" label="经度" show-overflow-tooltip/>-->
      <!--      <el-table-column prop="accountId" label="账户信息" show-overflow-tooltip/>-->
      <!--      <el-table-column prop="accountName" label="账户名称"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="statusFlag" label="状态 0-停用 1-启用 2-备用"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="delFlag" label="是否删除 0-否 1-是"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="createUser" label="创建人"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="createTime" label="创建时间"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="updateTime" label="修改时间"-->
      <!--                       show-overflow-tooltip/>-->
      <!--      <el-table-column prop="remark" label="备注" show-overflow-tooltip/>-->

      <el-table-column fixed="right" label="操作" width="260"
                       v-if="userInfo.userType == 0">
        <!--        <template #header>-->
        <!--          <el-input v-model="params.search" @keyup.enter.native="searchData" placeholder="搜索角色名称/介绍"/>-->
        <!--        </template>-->
        <template #default="scope">
          <el-button link type="danger" :icon="Delete" size="small" @click="showDeleteDialog(scope.row.id)">删除
          </el-button>
          <el-button link type="primary" :icon="Edit" size="small"
                     @click="editDialog(scope.row)">编辑
          </el-button>
          <el-button link type="primary" :icon="Edit" size="small"
                     @click="belongtoDialog(scope.row)">归属区域合伙人
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:currentPage="params.current"
                   v-model:page-size="params.size"
                   :page-sizes="[100, 200, 300, 400]"
                   layout="sizes, prev, pager, next" :total="tableData.total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"/>
  </el-card>

  <!-- 新增或者修改页面-->
  <RetailShopAddOrEdit
      @closeEditDialog="closeEditDialog"
      :addOrEditVisible="addOrEditVisible"
      :ruleForm="ruleForm"
      :addDataType="addDataType"></RetailShopAddOrEdit>


  <el-dialog v-model="belongtoVisible" title="归属区域合伙人" width="500">
    <el-form :model="belongform">
      <el-form-item label="商户名称">
        <el-input disabled v-model="belongform.poiName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="归属区域合伙人">
        <el-select v-model="belongform.adminId" placeholder="区域合伙人">
          <el-option v-for="(item,index) in belongList" :label="item.name"
                     :value=item.id>
            <span style="float: left">{{ item.name }}</span>
            <span
                style=" float: right;color: var(--el-text-color-secondary);font-size: 13px;">
            {{
                item.auditStatus == 1 ? '审核通过' :
                    item.auditStatus == 0 ? '待审核' :
                        item.auditStatus == 2 ? '审核不通过' : ''
              }}
             </span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="belongtoVisible = false">取消</el-button>
        <el-button type="primary" @click="belongtoComfirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="cityVisible" title="变更城市" width="500">
    <el-form :model="cityform">
      
      <el-form-item label="城市">
        <el-select v-model="cityform.city" placeholder="请选择归属城市" style="width:100%">
          <el-option label="南通" value="南通"></el-option>
          <el-option label="无锡" value="无锡"></el-option>
          <el-option label="徐州" value="徐州"></el-option>
          <el-option label="连云港" value="连云港"></el-option>
          <el-option label="盐城" value="盐城"></el-option>
          <el-option label="上海" value="上海"></el-option>
          <!--              <el-option label="苏州" value="苏州"></el-option>-->
          <!--              <el-option label="常州" value="常州"></el-option>-->
          <!--              <el-option label="常州" value="常州"></el-option>-->
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cityVisible = false">取消</el-button>
        <el-button type="primary" @click="cityComfirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  
</template>

<script lang="ts" setup>
import {ElTable, ElMessage, ElMessageBox} from 'element-plus'
import {onMounted, computed, reactive, ref} from 'vue'
import {Params, Result} from "@/apis/model/common/common.interfaces"
import {Delete, Edit, Search, Plus, EditPen} from '@element-plus/icons-vue'
import RetailShopAddOrEdit from './retailShopAddOrEdit.vue'
import {RetailShop} from "@/apis/model/shop/RetailShopModel";
import {
  deleteRetailShopById, pageExports,
  retailShopPage, updatecityBelong,
  updateShopBelong
} from "@/apis/http/shop/RetailShopHttp";
import {adminPage, adminSimpleTree} from "@/apis/http/system/AdminHttp";

import {userStore} from "@/store";
import {Admin} from "@/apis/model/system/AdminModel";
import {sysAdminVerifyExportPage} from "@/apis/http/order/SysAdminVerifyHttp";

const store = userStore();
const userInfo = store.userInfo;


// 查询
const params: Params = reactive({
  current: 1,
  size: 10,
  search: '',
  entity: {
    userType: userInfo.userType
  } as RetailShop
})

const ruleForm = ref<RetailShop>({} as RetailShop)

// AddOrEditVisible
const addOrEditVisible = ref(false)

// table 表数据
const tableData: any = ref({});

// 加载数据
const loading = ref(true)
const addDataType = ref('add');
const adminTrees = ref([])

const belongtoVisible = ref(false);
const belongform = ref({} as RetailShop)
const belongList = ref([] as Admin[])

const belongtoDialog = (row: RetailShop) => {
  belongform.value = row;
  belongtoVisible.value = true
}

const belongtoComfirm = () => {
  if (!belongform.value.adminId) {
    ElMessage.error('请选择区域合伙人！');
    return false;
  }

  updateShopBelong(belongform.value).then(res => {
    ElMessage({
      message: '更改归属成功！',
      type: 'success',
    })
    initList();
    belongtoVisible.value = false;
  }).catch(e => {
    belongtoVisible.value = false;
  })
}

const cityVisible = ref(false);
const cityform = ref({} as RetailShop)
const multipleSelection = ref<RetailShop[]>([])
const updateCity = () => {
  cityVisible.value = true;
}

const cityComfirm = () => {
  if (!cityform.value.city) {
    ElMessage.error('请选择城市！');
    return false;
  }
  
  let shopIds:number[] = [];
  multipleSelection.value.forEach(sh => {shopIds.push(sh.id)});
  cityform.value.ids = shopIds;
  updatecityBelong(cityform.value).then(res => {
    ElMessage({
      message: '更改城市成功！',
      type: 'success',
    })
    initList();
    cityVisible.value = false;
  }).catch(e => {
    cityVisible.value = false;
  })
}

const handleSelectionChange = (val: RetailShop[]) => {
  multipleSelection.value = val
}

const searchExportData = () => {
  loading.value = true
  ElMessage('正在导出，请稍后......')
  pageExports(params).then((res) => {
    let blob = new Blob([res],
        {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"}
    ); // 为blob设置文件类型，这里以.xlsx为例
    let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
    let a = document.createElement("a");
    a.href = url;
    a.download = '核销数据';
    a.click();
    // 释放这个临时的对象url
    window.URL.revokeObjectURL(url);
    loading.value = false
  })
}


/**
 * 初始化数据
 */
const initList = () => {
  loading.value = true
  retailShopPage(params).then((res: Result) => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      tableData.value = data
    }
    loading.value = false
  })
}

const initYwyList = async () => {

  const ywyParams: Params = reactive({
    current: 1,
    size: 1000,
    search: '',
    entity: {
      userType: 1
    } as Admin
  })

  await adminPage(ywyParams).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      belongList.value = data.list
    }
  })
}


/**
 * search 查询数据
 */
const searchData = () => {
  initList()
}

/**
 * 每页数据量改变查询数据
 * @param val
 */
const handleSizeChange = (val: number) => {
  params.size = val
  initList()
}

/**
 * 分页查询数据
 * @param val
 */
const handleCurrentChange = (val: number) => {
  params.current = val
  initList()
}

/**
 * 添加弹出
 */
const addDialog = () => {
  addOrEditVisible.value = true
  ruleForm.value = {
    shopSource: 0
  } as RetailShop
  addDataType.value = 'add'
}

//修改弹窗
const editDialog = (row: RetailShop) => {
  addOrEditVisible.value = true
  ruleForm.value = row
  let sanitaryLicensePhotos = ruleForm.value.sanitaryLicensePhotos;
  let sanitaryLicensePhotoss = [] as any[];
  if (sanitaryLicensePhotos != null && sanitaryLicensePhotos.length > 0) {
    sanitaryLicensePhotos.forEach(s => {
      sanitaryLicensePhotoss.push({
        name: 'sanit' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.sanitaryLicensePhotoss = sanitaryLicensePhotoss

  let businessLicensePhotos = ruleForm.value.businessLicensePhotos;
  let businessLicensePhotoss = [] as any[];
  if (businessLicensePhotos != null && businessLicensePhotos.length > 0) {
    businessLicensePhotos.forEach(s => {
      businessLicensePhotoss.push({
        name: 'busi' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.businessLicensePhotoss = businessLicensePhotoss

  let corporationPhotos = ruleForm.value.corporationPhotos;
  let corporationPhotoss = [] as any[];
  if (corporationPhotos != null && corporationPhotos.length > 0) {
    corporationPhotos.forEach(s => {
      corporationPhotoss.push({
        name: 'busi' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.corporationPhotoss = corporationPhotoss

  let doorPhotos = ruleForm.value.doorPhotos;
  let doorPhotoss = [] as any[];
  if (doorPhotos != null && doorPhotos.length > 0) {
    doorPhotos.forEach(s => {
      doorPhotoss.push({
        name: 'doors' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.doorPhotoss = doorPhotoss

  let evnPhotos = ruleForm.value.evnPhotos;
  let evnPhotoss = [] as any[];
  if (evnPhotos != null && evnPhotos.length > 0) {
    evnPhotos.forEach(s => {
      evnPhotoss.push({
        name: 'doors' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.evnPhotoss = evnPhotoss

  let douyinPhotos = ruleForm.value.douyinPhotos;
  let douyinPhotoss = [] as any[];
  if (douyinPhotos != null && douyinPhotos.length > 0) {
    douyinPhotos.forEach(s => {
      douyinPhotoss.push({
        name: 'doors' + (new Date().getTime()) + '.jpeg',
        url: s
      })
    })
  }
  ruleForm.value.douyinPhotoss = douyinPhotoss


  addDataType.value = 'edit'
}

// 关闭修改弹窗
const closeEditDialog = (e: any) => {
  addOrEditVisible.value = e.addOrEditVisible
  if (e.refushList = true) {
    params.current = 1;
    initList();
  }
}

/**
 * 弹出删除对话框
 */
const showDeleteDialog = (id: number) => {
  ElMessageBox.confirm('是否删除?', '提醒', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteRetailShopById(id).then((res: Result) => {
      const code = res.code;
      if (code == 200) {
        ElMessage({
          message: '删除数据成功！',
          type: 'success',
        })
        initList();
      } else {
        ElMessage.error('删除数据失败！');
      }
    })
  }).catch(() => {
    // ElMessage({
    //   type: 'info',
    //   message: 'Delete canceled',
    // })
  })
}

// const initAdminTree = () => {
//   adminSimpleTree().then(res => {
//     adminTrees.value = res.data;
//   })
// }

onMounted(async () => {
  // initAdminTree();
  await initYwyList();
  initList()
})
</script>

<style>
</style>
